package com.opengw.http;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;

import com.opengw.configuration.config.RouteConfig;
import com.opengw.configuration.route.Route;
import com.opengw.exception.OpenGWException;

public class HTTPResponse {
	private int contentLength;
	private HashMap<String, String> responseHeaders;
	private byte[] content;
	private int responseCode;
	
	public HTTPResponse(HTTPConnection connection, Route route) throws OpenGWException{
		try{
			this.responseHeaders = new HashMap<String, String>();
			connection.setResponseHeaders(this);	
			this.responseCode = connection.getHTTPCode();
			this.content = connection.getContent();
			
			for(RouteConfig config : route.getRouteConfigList()){
				if(config.isControlResponse())
					config.doControlResponse(this);
				if(config.isChangeResponse())
					config.doChangeResponse(this);
			}
		} catch (Exception e) {
			throw new OpenGWException(e);
		}
	}
		
	public HTTPResponse(HashMap<String, String> responseHeaders, byte[] content){
		this.responseHeaders = responseHeaders;
		this.content = content;
		this.responseCode = 200;
		if(content == null)
			this.contentLength = -1;
		else
			this.contentLength = content.length;
	}
	
	public void sendResponse(HttpServletResponse response) throws IOException{
		Iterator<String> iterator = responseHeaders.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			response.setHeader(key, responseHeaders.get(key));
		}
		
		response.setStatus(responseCode);
		
		if(content != null){
			response.setContentLength(contentLength);
			response.getOutputStream().write(content);
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
	}
	
	public void setResponseHeader(String key, String value){
		this.responseHeaders.put(key, value);
	}
	
	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}
	public int getContentLength() {
		return contentLength;
	}
	public void setResponseHeaders(HashMap<String, String> responseHeaders) {
		this.responseHeaders = responseHeaders;
	}
	public void removeResponseHeader(String key){
		this.responseHeaders.remove(key);
	}
	public HashMap<String, String> getResponseHeaders() {
		return responseHeaders;
	}
	public void setContent(byte[] content) {
		this.content = content;
	}
	public byte[] getContent() {
		return content;
	}
	public void setResponseCode(int responseCode) {
		this.responseCode = responseCode;
	}
	public int getResponseCode() {
		return responseCode;
	}

}
